package cn.lg.soar.boot.fc.controller;

import cn.lg.soar.boot.fc.entity.TenancyRoom;
import cn.lg.soar.boot.fc.entity.TenancyRoomRecord;
import cn.lg.soar.boot.fc.entity.vo.HousingRecordVo;
import cn.lg.soar.boot.fc.entity.vo.RoomVo;
import cn.lg.soar.boot.fc.entity.vo.TenancyRoomRecordVo;
import cn.lg.soar.boot.fc.entity.vo.TenancyRoomVo;
import cn.lg.soar.boot.fc.service.ProcessService;
import cn.lg.soar.boot.fc.service.RoomService;
import cn.lg.soar.boot.fc.service.TenancyRoomService;
import cn.lg.soar.common.data.msg.I18n;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.core.annotations.IdempotentByParam;
import cn.lg.soar.core.annotations.constraints.group.Create;
import cn.lg.soar.core.annotations.constraints.group.Update;
import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.mvc.enums.ControllerConst;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.mvc.annotations.Log;
import cn.lg.soar.system.auth.entity.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.boot.fc.entity.ProcessApply;
import cn.lg.soar.boot.fc.service.ProcessApplyService;

/**
 * 用户申请审批表
 * @author ZhuanZ（无密码）
 * @since 2025-01-15
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Api(tags = "用户申请审批表")
@Validated
@RestController
@RequestMapping("fc/processApply")
public class ProcessApplyController extends BaseController<ProcessApply, ProcessApplyService> {

    @Autowired
    protected TenancyRoomService tenancyRoomService;
    @Resource
    private RoomService roomService;
    @Autowired
    protected ProcessService processService;

    private SqueryWapper<TenancyRoom> tenancyRoomWapper;

    private SqueryWapper<cn.lg.soar.boot.fc.entity.Process> processWapper;

    @Override
    protected Serializable getId(ProcessApply entity) {
        return entity.getId();
    }

    @Log(value = "新增用户申请审批表", data = "#p0", dataId = "#$r.data")
    @IdempotentByParam("#p0")
    @ApiOperation(value = ControllerConst.CREATE_NAME)
    @RequestMapping(path = "create", method = RequestMethod.POST)
    public HttpResult<Serializable> create(@RequestBody @Validated(Create.class) ProcessApply data) {
        return super.createResult(data);
    }

    @Log(value = "修改用户申请审批表", data = "#p0", dataId = "#p0.id")
    @ApiOperation(value = ControllerConst.UPDATE_NAME)
    @RequestMapping(path = "update", method = RequestMethod.POST)
    public HttpResult<Void> update(@RequestBody @Validated(Update.class) ProcessApply data) {
        return super.updateResult(data);
    }

    @Log(value = "删除用户申请审批表", data = "#p0")
    @ApiOperation(value = ControllerConst.REMOVE_NAME, notes = "根据 id 删除")
    @RequestMapping(path = "remove", method = RequestMethod.POST)
    public HttpResult<Void> remove(@RequestBody List<Long> ids) {
        return super.removeResult(ids);
    }

    @ApiOperation(value = ControllerConst.DETAIL_NAME, notes = "根据 ID 获取一条数据")
    @RequestMapping(path = "detail", method = RequestMethod.GET)
    public HttpResult<ProcessApply> detail(@RequestParam Long id) {
        return super.detailResult(id);
    }

    @ApiOperation(value = ControllerConst.QUERY_NAME, notes = "多功能查询（分页、列表、统计）")
    @RequestMapping(path = "query", method = RequestMethod.GET)
    public HttpResult<PageResult<ProcessApply>> query(PageQuery pageQuery, QueryParams params){
        return super.queryResult(pageQuery, params);
    }

    @Log(value = "导出用户申请审批表")
    @ApiOperation(value = ControllerConst.EXPORT_NAME)
    @RequestMapping(path = "export", method = RequestMethod.GET)
    public void exports(String filename, QueryParams params, HttpServletResponse resp){
        super.exportExcel(filename, params, resp);
    }

    @Log(value = "导入用户申请审批表")
    @ApiOperation(value = ControllerConst.IMPORT_NAME)
    @RequestMapping(path = "import", method = RequestMethod.POST)
    public HttpResult<Void> imports(HttpServletRequest req){
        return super.importExcel(req);
    }


    @ApiOperation(value = "用户房源记录")
    @RequestMapping(path = "housingRecord", method = RequestMethod.GET)
    public HttpResult<PageResult<HousingRecordVo>> housingRecord(PageQuery pageQuery, @RequestParam Long userId) {
        PageResult<HousingRecordVo> pageResult = new PageResult<>();
        if (processWapper == null) {
            processWapper = new SqueryWapper<>(cn.lg.soar.boot.fc.entity.Process.class);
        }
        QueryWrapper<cn.lg.soar.boot.fc.entity.Process> processWrapper = Wrappers.query();
        List<String> f0 = new ArrayList<>();
        f0.add("examineType-eq~1");
        processWapper.setWhere(f0, processWrapper);
        List<cn.lg.soar.boot.fc.entity.Process> processList = processService.list(processWrapper);
        if(!processList.isEmpty()){
            String[] processIds = new String[processList.size()];
            for (int i=0;i<processList.size();i++) {
                processIds[i] = String.valueOf(processList.get(i).getId());
            }
            QueryParams params = new QueryParams();
            List<String > f1 = new ArrayList<>();
            f1.add("userId-eq~"+userId);
            f1.add("processId-in~"+ Arrays.toString(processIds).replaceAll(",","~"));
            params.setF(f1);
            List<HousingRecordVo> list = new ArrayList<>();
            List<ProcessApply> processApplyQuery = super.queryResult(pageQuery, params).getData().getList();
            for (ProcessApply apply : processApplyQuery) {
                HousingRecordVo recordVo = new HousingRecordVo();
                BeanUtils.copyProperties(apply, recordVo);
                if (tenancyRoomWapper == null) {
                    tenancyRoomWapper = new SqueryWapper<>(TenancyRoom.class);
                }
                QueryWrapper<TenancyRoom> wrapper = Wrappers.query();
                List<String> f = new ArrayList<>();
                f.add("formApplyId-eq~"+apply.getId());
                tenancyRoomWapper.setWhere(f, wrapper);
                List<TenancyRoom> tenancyRoomList = tenancyRoomService.list(wrapper);
                if(!tenancyRoomList.isEmpty()){
                    TenancyRoom tenancyRoom = tenancyRoomList.get(0);
                    RoomVo roomVo = roomService.getVoData(tenancyRoom.getRoomId());
                    String roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                            +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
                    recordVo.setRoomInfo(roomInfo);
                    recordVo.setArea(roomVo.getArea());
                    recordVo.setLivingRoom(roomVo.getLivingRoom());
                    recordVo.setOrient(roomVo.getOrient());
                    recordVo.setOwnershipCode(roomVo.getOwnershipCode());
                    recordVo.setContacts(roomVo.getContacts());
                    recordVo.setPhone(roomVo.getPhone());
                    list.add(recordVo);
                }
            }
            pageResult.setList(list);
        }

        return HttpResult.data(pageResult);
    }

    @ApiOperation(value = "用户退租记录")
    @RequestMapping(path = "exitTenancyRecord", method = RequestMethod.GET)
    public HttpResult<PageResult<HousingRecordVo>> exitTenancyRecord(PageQuery pageQuery, @RequestParam Long userId) {
        PageResult<HousingRecordVo> pageResult = new PageResult<>();
        if (processWapper == null) {
            processWapper = new SqueryWapper<>(cn.lg.soar.boot.fc.entity.Process.class);
        }
        QueryWrapper<cn.lg.soar.boot.fc.entity.Process> processWrapper = Wrappers.query();
        List<String> f0 = new ArrayList<>();
        f0.add("examineType-eq~2");
        processWapper.setWhere(f0, processWrapper);
        List<cn.lg.soar.boot.fc.entity.Process> processList = processService.list(processWrapper);
        if(!processList.isEmpty()){
            String[] processIds = new String[processList.size()];
            for (int i=0;i<processList.size();i++) {
                processIds[i] = String.valueOf(processList.get(i).getId());
            }
            QueryParams params = new QueryParams();
            List<String > f1 = new ArrayList<>();
            f1.add("userId-eq~"+userId);
            f1.add("processId-in~"+ Arrays.toString(processIds).replaceAll(",","~"));
            params.setF(f1);
            List<HousingRecordVo> list = new ArrayList<>();
            List<ProcessApply> processApplyQuery = super.queryResult(pageQuery, params).getData().getList();
            for (ProcessApply apply : processApplyQuery) {
                HousingRecordVo recordVo = new HousingRecordVo();
                BeanUtils.copyProperties(apply, recordVo);
                if (tenancyRoomWapper == null) {
                    tenancyRoomWapper = new SqueryWapper<>(TenancyRoom.class);
                }
                QueryWrapper<TenancyRoom> wrapper = Wrappers.query();
                List<String> f = new ArrayList<>();
                f.add("formApplyId-eq~"+apply.getId());
                tenancyRoomWapper.setWhere(f, wrapper);
                List<TenancyRoom> tenancyRoomList = tenancyRoomService.list(wrapper);
                if(!tenancyRoomList.isEmpty()){
                    TenancyRoom tenancyRoom = tenancyRoomList.get(0);
                    RoomVo roomVo = roomService.getVoData(tenancyRoom.getRoomId());
                    String roomInfo = roomVo.getCampusEasyVo().getName()+"*"+roomVo.getBuildingEasyVo().getName()+"*"+roomVo.getUnitEasyVo().getName()+"*"
                            +roomVo.getFloorEasyVo().getName()+"*"+roomVo.getRoomCode();
                    recordVo.setRoomInfo(roomInfo);
                    recordVo.setArea(roomVo.getArea());
                    recordVo.setLivingRoom(roomVo.getLivingRoom());
                    recordVo.setOrient(roomVo.getOrient());
                    recordVo.setOwnershipCode(roomVo.getOwnershipCode());
                    recordVo.setContacts(roomVo.getContacts());
                    recordVo.setPhone(roomVo.getPhone());
                    list.add(recordVo);
                }
            }
            pageResult.setList(list);
        }

        return HttpResult.data(pageResult);
    }
}